package com.mk.property.controller;

import com.aliyuncs.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mk.property.common.R;
import com.mk.property.pojo.Owner;
import com.mk.property.service.OwnerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/owner")
public class OwnerController {
    @Autowired
    OwnerService ownerService;

    /**
     * 分页查询
     *
     * @param page     当前查询页码
     * @param pageSize 每页展示的记录数
     * @param name     员工姓名 - 可选参数
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {
        log.info("page = {},pageSize = {},name = {}", page, pageSize, name);
        //构造分页构造器
        Page pageInfo = new Page(page, pageSize);

        //条件构造器
        LambdaQueryWrapper<Owner> lqw = new LambdaQueryWrapper<>();
        //name不为空才会执行下面的语句
        lqw.like(StringUtils.isNotEmpty(name), Owner::getName, name);
        //TODO 这里以后可以加个排序,数据库里面加个updateTime字段

        //执行查询
        ownerService.page(pageInfo, lqw);
        return R.success(pageInfo);
    }

    @GetMapping("/id")
    public R<List> getOwnerIdAndNameList() {
        //查询全部业主数据
        List<Owner> owners = ownerService.list();
        return R.success(owners);
    }

    /**
     * 新增业主
     *
     * @param owner
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody Owner owner) {
        log.info("新增业主,业主信息为{}", owner.toString());
        ownerService.save(owner);
        return R.success("新增业主成功");
    }

    /**
     * 根据id查询业主信息
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<Owner> getById(@PathVariable Long id) {
        log.info("根据id查询业主信息");
        Owner owner = ownerService.getById(id);
        if (owner != null) {
            return R.success(owner);
        }
        return R.error("没有查询到对应业主信息");
    }

    @PutMapping
    public R<String> update(@RequestBody Owner owner) {
        log.info(owner.toString());
        ownerService.updateById(owner);
        return R.success("业主信息修改成功");
    }
}
